document.addEventListener('DOMContentLoaded', function () {
    const jobPostForm = document.getElementById('jobPostForm');
    if (jobPostForm) {
        jobPostForm.addEventListener('submit', function(e) {
            e.preventDefault();
            submitJobForm();
        });
    }
    // 切换模块显示
    window.showModule = function (moduleId) {
        const modules = document.querySelectorAll('.module');
        modules.forEach(module => module.style.display = 'none');
        document.getElementById(moduleId).style.display = 'block';

        // 如果切换到职位管理模块，加载职位列表
        if (moduleId === 'job-management') {
            loadJobList();
        }
    };

    // 加载职位列表
    function loadJobList() {
        const token = localStorage.getItem('token');
        if (!token) {
            // window.location.href = 'company-login.html'; // 注释掉自动跳转
            return;
        }

        fetch('http://localhost:3001/api/jobs/company/my-jobs', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    renderJobList(data.data);
                } else {
                    showError(data.message || '获取职位列表失败');
                }
            })
            .catch(error => {
                console.error('获取职位列表时出错:', error);
                showError('获取职位列表失败，请稍后重试');
            });
    }

    // 渲染职位列表
    function renderJobList(jobs) {
        const container = document.getElementById('job-list-container');
        if (!container) return;

        if (jobs.length === 0) {
            container.innerHTML = '<div class="no-data">暂无职位数据</div>';
            return;
        }

        let html = `
            <table class="job-table">
                <thead>
                    <tr>
                        <th>职位名称</th>
                        <th>薪资范围</th>
                        <th>工作地点</th>
                        <th>工作类型</th>
                        <th>发布时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
        `;

        jobs.forEach(job => {
            const statusClass = job.status === 'active' ? 'status-active' : 'status-inactive';
            const statusText = job.status === 'active' ? '已上架' : '已下架';
            const publishDate = new Date(job.createdAt).toLocaleDateString();

            html += `
                <tr>
                    <td>${escapeHtml(job.title)}</td>
                    <td>${escapeHtml(job.salaryRange)}</td>
                    <td>${escapeHtml(job.location)}</td>
                    <td>${getJobTypeText(job.jobType)}</td>
                    <td>${publishDate}</td>
                    <td><span class="status ${statusClass}">${statusText}</span></td>
                    <td>
                        <button class="btn view-btn" onclick="viewJob(${job.id})">查看</button>
                        <button class="btn edit-btn" onclick="editJob(${job.id})">编辑</button>
                        <button class="btn ${job.status === 'active' ? 'down-btn' : 'up-btn'}" onclick="toggleJobStatus(${job.id}, '${job.status === 'active' ? 'inactive' : 'active'}')">${job.status === 'active' ? '下架' : '上架'}</button>
                        <button class="btn delete-btn" onclick="deleteJob(${job.id})">删除</button>
                    </td>
                </tr>
            `;
        });

        html += `
                </tbody>
            </table>
        `;
        container.innerHTML = html;
    }

    // 辅助函数：转义HTML特殊字符
    function escapeHtml(text) {
        return text
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    // 职位发布表单处理
    function submitJobForm() {
        const token = localStorage.getItem('token');
        if (!token) {
            // window.location.href = 'company-login.html'; // 注释掉自动跳转
            return;
        }

        // 收集表单数据
        const jobData = {
            title: document.getElementById('job-title').value.trim(),
            industry: document.getElementById('industry').value,
            location: document.getElementById('location').value.trim(),
            salaryRange: document.getElementById('salary-range').value.trim(),
            experience: document.getElementById('experience').value,
            education: document.getElementById('education').value,
            description: document.getElementById('job-description').value.trim(),
            requirements: document.getElementById('requirements').value.trim(),
            benefits: document.getElementById('benefits').value.trim(),
            jobType: document.getElementById('job-type').value
        };

        // 表单验证
        let isValid = true;
        clearAllErrors();

        if (!jobData.title) {
            showFieldError('job-title', '请输入职位名称');
            isValid = false;
        }

        if (!jobData.industry) {
            showFieldError('industry', '请选择行业');
            isValid = false;
        }

        if (!jobData.location) {
            showFieldError('location', '请输入工作地点');
            isValid = false;
        }

        if (!jobData.salaryRange) {
            showFieldError('salary-range', '请输入薪资范围');
            isValid = false;
        }

        if (!jobData.experience) {
            showFieldError('experience', '请选择工作经验');
            isValid = false;
        }

        if (!jobData.education) {
            showFieldError('education', '请选择学历要求');
            isValid = false;
        }

        if (!jobData.description) {
            showFieldError('job-description', '请输入职位描述');
            isValid = false;
        }

        if (!jobData.requirements) {
            showFieldError('requirements', '请输入任职要求');
            isValid = false;
        }

        if (!isValid) return;

        // 提交表单数据
        fetch('http://localhost:3001/api/jobs', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(jobData)
        })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message || '创建职位失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showSuccess('职位发布成功');
                    jobPostForm.reset();
                    // 先切换到职位管理界面，再刷新列表
                    showModule('job-management');
                    setTimeout(loadJobList, 200); // 延迟刷新，确保DOM切换完成
                } else {
                    showError(data.message || '创建职位失败');
                }
            })
            .catch(error => {
                console.error('发布职位时出错:', error);
                showError(error.message || '发布职位失败，请稍后重试');
            });
    }

    // 错误提示辅助函数
    function showFieldError(fieldId, message) {
        const field = document.getElementById(fieldId);
        if (field) {
            const errorElement = field.nextElementSibling;
            if (errorElement && errorElement.classList.contains('error-message')) {
                errorElement.textContent = message;
                errorElement.style.display = 'block';
            }
        }
    }

    function clearAllErrors() {
        const errorElements = document.querySelectorAll('.error-message');
        errorElements.forEach(el => {
            el.textContent = '';
            el.style.display = 'none';
        });
    }

    function showSuccess(message) {
        alert(message); // 实际项目中可替换为更友好的通知组件
    }

    function showError(message) {
        alert(message); // 实际项目中可替换为更友好的通知组件
    }

    function getJobTypeText(type) {
        const typeMap = {
            'full-time': '全职',
            'part-time': '兼职',
            'internship': '实习'
        };
        return typeMap[type] || type;
    }

    // 辅助函数：转义HTML特殊字符
    function escapeHtml(text) {
        return text
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    // 在文件末尾添加 deleteJob 函数
    window.deleteJob = function (jobId) {
        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = 'company-login.html';
            return;
        }
        if (!confirm('确定要删除该职位吗？')) return;
        fetch(`http://localhost:3001/api/jobs/${jobId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess('删除成功');
                    loadJobList();
                } else {
                    showError(data.message || '删除失败');
                }
            })
            .catch(error => {
                console.error('删除职位时出错:', error);
                showError('删除失败，请稍后重试');
            });
    }

    window.viewJob = function(jobId) {
        fetch(`http://localhost:3001/api/jobs/${jobId}`)
            .then(res => res.json())
            .then(job => {
                // 构建弹窗内容
                const html = `
                    <h3>${job.title}</h3>
                    <p><b>行业：</b>${job.industry || ''}</p>
                    <p><b>描述：</b>${job.description || ''}</p>
                    <p><b>薪资范围：</b>${job.salary_range || job.salaryRange || ''}</p>
                    <p><b>任职要求：</b>${job.requirements || ''}</p>
                    <p><b>工作地点：</b>${job.location || ''}</p>
                    <p><b>类型：</b>${job.job_type || job.jobType || ''}</p>
                    <p><b>经验：</b>${job.experience || ''}</p>
                    <p><b>学历：</b>${job.education || ''}</p>
                    <p><b>福利：</b>${job.benefits || ''}</p>
                    <p><b>亮点：</b>${job.highlights || ''}</p>
                    <p><b>公司简介：</b>${job.company_intro || ''}</p>
                `;
                showModal(html);
            });
    }

    // 简单弹窗函数
    function showModal(content) {
        let modal = document.getElementById('job-detail-modal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'job-detail-modal';
            modal.style.position = 'fixed';
            modal.style.left = '0';
            modal.style.top = '0';
            modal.style.width = '100vw';
            modal.style.height = '100vh';
            modal.style.background = 'rgba(0,0,0,0.4)';
            modal.style.display = 'flex';
            modal.style.alignItems = 'center';
            modal.style.justifyContent = 'center';
            modal.innerHTML = `<div id="job-detail-content" style="background:#fff;padding:32px;border-radius:8px;max-width:500px;min-width:300px;position:relative;">
                <button id="close-job-detail" style="position:absolute;right:10px;top:10px;">关闭</button>
                <div id="job-detail-body"></div>
            </div>`;
            document.body.appendChild(modal);
            document.getElementById('close-job-detail').onclick = function() {
                modal.style.display = 'none';
            };
        }
        document.getElementById('job-detail-body').innerHTML = content;
        modal.style.display = 'flex';
    }
});
    